//
//  M_PhotoHuDongViewController.m
//  Model
//
//  Created by apple on 2018/7/13.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "M_PhotoHuDongViewController.h"

#import "M_PhotoHuDongTableViewCell.h"
#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "MJRefreshFooter.h"
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface M_PhotoHuDongViewController ()<UITableViewDelegate, UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property(nonatomic,strong)UITextView *textView;

@property(nonatomic,strong)UIView *inputBackgroundView;

@property(nonatomic,strong)UIView *toolView;

@property(nonatomic,assign)CGFloat keyboardHeight;
@property (nonatomic, strong) UIButton *faSongBtn;//发送

@property (nonatomic, assign) NSInteger page2;


@end

@implementation M_PhotoHuDongViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:NO];

    __weak typeof(self) weakself = self;
    [self creationData];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakself creationDataJZ];
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself creationData];
        
        [self.tableView.mj_header beginRefreshing];
    }];
    
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    [self regeditCell];
   _page2 = 1;
    CGFloat width=ScreenWidth;
    //736
    CGFloat height=ScreenHeight-64-(KIsiPhoneX?80:40);
    
    self.inputBackgroundView.frame=CGRectMake(0, height, width, 40);
    [self.view addSubview:self.inputBackgroundView];
    
    self.textView.frame=CGRectMake(15, 5, width-30-50, 30);
    [self.inputBackgroundView addSubview:self.textView];
    self.faSongBtn = [[UIButton alloc] init];
    [self.inputBackgroundView addSubview:self.faSongBtn];
    [self.faSongBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.inputBackgroundView).with.offset(-12);
        make.bottom.equalTo(self.inputBackgroundView).with.offset(-5);
        make.height.offset(30);
        
    }];
    [self.faSongBtn setBackgroundImage:[UIImage imageNamed:@"bg_send"] forState:UIControlStateNormal];
    [self.faSongBtn setTitle:@"发送" forState:UIControlStateNormal];
    self.faSongBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.faSongBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self.faSongBtn addTarget:self action:@selector(fasongClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.textView.inputAccessoryView=self.toolView;
    //键盘的frame即将发生变化时立刻发出该通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.title = @"互动";
    
    self.view.backgroundColor = getColor(@"f7f7f7");

    // Do any additional setup after loading the view.
}
- (void)fasongClick{
    
    [self.textView resignFirstResponder];
    if (self.textView.text.length == 0) {
        
//        [PublicFunction showAlert:nil message:@"评论不能为空" duration:5.0f];
        return;
        
    }
    
    CGFloat width=ScreenWidth;
    //736
    CGFloat height=ScreenHeight-64-(KIsiPhoneX?80:40);

    self.inputBackgroundView.frame=CGRectMake(0, height, width, 40);
    self.textView.frame=CGRectMake(15, 5, width-30-50, 30);
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];

    NSString *type = [NSString stringWithFormat:@"%ld", (long)self.albumid];
    [productParams setValue:type forKey:@"albumid"];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:token forKey:@"token"];
    [productParams setValue:self.textView.text forKey:@"content"];
    [[MNetworkHandler sharedInstance]conURL:setcomment networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"Status"]intValue]==200) {
            
            [self creationData];
 
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
            //            [hud removeFromSuperview];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        //        [hud removeFromSuperview];
    }];
    
    self.textView.text = @"";
    [self.textView resignFirstResponder];
    
    
    
    
}
- (void)creationView{
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 10, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-50-64);
    
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = getColor(@"f7f7f7");
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 400;

    UIView *footView = [[UIView alloc] init];
    [self.view addSubview:footView];
    footView.backgroundColor = [UIColor whiteColor];
    [footView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(50);
 
    }];
    
    
    
    
    
    
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return  _dataArr;
}
- (void)creationData{
    
    [self.tableView.mj_header endRefreshing];
    
    
    _page2 = 1;
    NSString *strPage = [NSString stringWithFormat:@"%ld", (long)_page2];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    
    [productParams setValue:strPage forKey:@"page"];
    
    //    [productParams setValue:@"10" forKey:@"pagesize"];
    NSString *type = [NSString stringWithFormat:@"%ld", (long)self.albumid];
    [productParams setValue:type forKey:@"albumid"];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:token forKey:@"token"];
    [[MNetworkHandler sharedInstance]conURL:comments networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"Status"]intValue]==200) {
            
            self.dataArr = [returnData objectForKey:@"Data"];
            
            
            NSLog(@"DDDDDDDDDDDD%@", self.dataArr);
            
            [self.tableView reloadData];
            //
            //
            //            [hud removeFromSuperview];
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
            //            [hud removeFromSuperview];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        //        [hud removeFromSuperview];
    }];
    
    
    //    }
    
    
    
}
- (void)creationDataJZ{
    
    _page2++;
    
    NSString *strPage = [NSString stringWithFormat:@"%ld", (long)_page2];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    
    [productParams setValue:strPage forKey:@"page"];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:token forKey:@"token"];
    //    [productParams setValue:@"10" forKey:@"pagesize"];
    NSString *type = [NSString stringWithFormat:@"%ld", (long)self.albumid];
    [productParams setValue:type forKey:@"albumid"];
    
    [[MNetworkHandler sharedInstance]conURL:comments networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"Status"]intValue]==200) {
            
            NSMutableArray *arr =[returnData objectForKey:@"Data"];
            
            if (arr.count == 0) {
                
                [self.tableView.mj_footer endRefreshing];
                
            }else {
                
                [self.dataArr addObjectsFromArray:arr];
                
                NSLog(@"JZJZJZJZJZJJZJZJZJZJZJJZJZ%@", self.dataArr);
                
                
            }
            //
            //
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
            //
        }
        //
        else {
            //
            //            [PublicFunction showAlert:nil message:@"没有更多照片" duration:5.0f];
            [self.tableView.mj_footer endRefreshing];
            //
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        
    }];
    //    }
    
    
}
-(UIView *)toolView{
    
    if (_toolView==nil) {
        _toolView=[UIView new];
        _toolView.backgroundColor=[UIColor colorWithRed:210/255.0 green:213/255.0 blue:219/255.0 alpha:1];
        _toolView.frame=CGRectMake(0, 0, ScreenWidth, 40);
        
//        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
//        [button setTitle:@"收起键盘" forState:UIControlStateNormal];
//        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        button.titleLabel.font=[UIFont systemFontOfSize:13];
//        [button setBackgroundImage:[UIImage imageNamed:@"button_share"] forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
//        button.frame=CGRectMake(ScreenWidth-60-15, (40-30)/2.0, 60, 30);
//        [_toolView addSubview:button];
        
        UIView *topLineView=[UIView new];
        topLineView.backgroundColor=[UIColor grayColor];
        topLineView.frame=CGRectMake(0, 0, ScreenWidth, 1);
        [_toolView addSubview:topLineView];
    }
    return _toolView;
}

-(void)buttonAction{
    
    [self.view endEditing:YES];
}

-(UIView *)inputBackgroundView{
    
    if (_inputBackgroundView==nil) {
        _inputBackgroundView=[UIView new];
        _inputBackgroundView.backgroundColor=[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    }
    return _inputBackgroundView;
}

-(UITextView *)textView{
    
    if (_textView==nil) {
        _textView=[[UITextView alloc]init];
        _textView.font=[UIFont systemFontOfSize:15];
        _textView.layer.cornerRadius=5;
        _textView.layer.masksToBounds=YES;
        _textView.layer.borderWidth=1;
        _textView.layer.borderColor=[UIColor lightGrayColor].CGColor;
        _textView.delegate=self;
    }
    return _textView;
}

-(void)keyboardChanged:(NSNotification *)notification{
    
    NSLog(@"%@",notification);
    //键盘即将消失的字典
    NSDictionary *willDisAppeardic=@{@"name":@"UIKeyboardWillChangeFrameNotification",
                                     @"userInfo": @{
                                             
                                             @"UIKeyboardAnimationCurveUserInfoKey" : @7,
                                             //键盘离开或进入屏幕的时间
                                             @"UIKeyboardAnimationDurationUserInfoKey": @"0.25",
                                             //键盘大小
                                             @"UIKeyboardBoundsUserInfoKey" : @"NSRect: {{0, 0}, {414, 311}}",
                                             @"UIKeyboardCenterBeginUserInfoKey" : @"NSPoint: {207, 580.5}",
                                             @"UIKeyboardCenterEndUserInfoKey" : @"NSPoint: {207, 891.5}",
                                             //键盘位置改变前的frame
                                             @"UIKeyboardFrameBeginUserInfoKey" : @"NSRect: {{0, 425}, {414, 311}}",
                                             //键盘位置改变后的frame
                                             @"UIKeyboardFrameEndUserInfoKey" : @"NSRect: {{0, 736}, {414, 311}}",
                                             @"UIKeyboardIsLocalUserInfoKey" : @1
                                             }
                                     };
    //键盘即将展示的字典
    NSDictionary *willAppeardic=@{@"name":@"UIKeyboardWillChangeFrameNotification",
                                  @"userInfo": @{
                                          
                                          @"UIKeyboardAnimationCurveUserInfoKey" : @7,
                                          @"UIKeyboardAnimationDurationUserInfoKey": @"0.25",
                                          @"UIKeyboardBoundsUserInfoKey" : @"NSRect: {{0, 0}, {414, 266}}",
                                          @"UIKeyboardCenterBeginUserInfoKey" : @"NSPoint: {207, 869}",
                                          @"UIKeyboardCenterEndUserInfoKey" : @"NSPoint: {207, 603}",
                                          @"UIKeyboardFrameBeginUserInfoKey" : @"NSRect: {{0, 736}, {414, 266}}",
                                          @"UIKeyboardFrameEndUserInfoKey" : @"NSRect: {{0, 470}, {414, 266}}",
                                          @"UIKeyboardIsLocalUserInfoKey" : @1
                                          }
                                  };
    
    CGRect frame=[notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    
    CGRect currentFrame=self.inputBackgroundView.frame;
    
    [UIView animateWithDuration:0.25 animations:^{
        //输入框最终的位置
        CGRect resultFrame;
        
        if (frame.origin.y==ScreenHeight) {
            resultFrame=CGRectMake(currentFrame.origin.x, ScreenHeight-64-currentFrame.size.height-(KIsiPhoneX?35:0), currentFrame.size.width, currentFrame.size.height);
            self.keyboardHeight=0;
        }else{
            resultFrame=CGRectMake(currentFrame.origin.x,ScreenHeight-64-currentFrame.size.height-frame.size.height, currentFrame.size.width, currentFrame.size.height);
            self.keyboardHeight=frame.size.height;
        }
        
        self.inputBackgroundView.frame=resultFrame;
    }];
    
}

-(void)textViewDidChange:(UITextView *)textView{
    
    NSString *str=textView.text;
    
    CGSize maxSize=CGSizeMake(textView.bounds.size.width, MAXFLOAT);
    //NSStringDrawingUsesLineFragmentOrigin:用于多行绘制，因为默认是单行绘制，如果不指定，那么绘制出来的高度就是0，也就是啥都不显示出来。
    
    //NSStringDrawingUsesFontLeading:计算行高时使用自体的间距，也就是行高=行距+字体高度
    
    //NSStringDrawingUsesDeviceMetrics:计算布局时使用图元字形（而不是印刷字体）
    
    //NSStringDrawingTruncatesLastVisibleLine:设置的string的bounds放不下文本的话，就会截断，然后在最后一个可见行后面加上省略号。如果NSStringDrawingUsesLineFragmentOrigin不设置的话，只设置这一个选项是会被忽略的。因为如果不设置NSStringDrawingUsesLineFragmentOrigin，默认是单行显示的。
    //(注意：我在弹出框的内容string中设置了这个字串，但是最后显示出来的时候并没有打省略号…,这是因为在当前方法boundingRectWithSize..中设置这个option并不会起作用的，因为当前方法只是测量string的大小，并不是绘制string，在drawWithRect:(CGRect)rect options:(NSStringDrawingOptions)options attributes:...这个方法中设置这个option就会起作用)
    
    
    //测量string的大小
    CGRect frame=[str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:textView.font} context:nil];
    //设置self.textView的高度，默认是30
    CGFloat tarHeight=30;
    //如果文本框内容的高度+10大于30也就是初始的self.textview的高度的话，设置tarheight的大小为文本的内容+10，其中10是文本框和背景view的上下间距；
    if (frame.size.height+10>30) {
        tarHeight=frame.size.height+10;
    }
    //如果self.textView的高度大于200时，设置为200，即最高位200
    if (tarHeight>200) {
        tarHeight=200;
    }
    
    CGFloat width=ScreenWidth;
    //设置输入框背景的frame
    self.inputBackgroundView.frame=CGRectMake(0, (ScreenHeight-64-self.keyboardHeight)-(tarHeight+10), width, tarHeight+10);
    //设置输入框的frame
    self.textView.frame=CGRectMake(15,(self.inputBackgroundView.bounds.size.height-tarHeight)/2 , width-30-50, tarHeight);
}

- (void)regeditCell{
    
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"M_PhotoHuDongTableViewCell" bundle:nil] forCellReuseIdentifier:@"M_PhotoHuDongTableViewCell"];

    
    
}
#pragma mark - ---------- Section的数量 ----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - ---------- 每个Section的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0;
}

#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
    
    
}
#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    
    
    M_PhotoHuDongTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"M_PhotoHuDongTableViewCell" forIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSMutableDictionary *dic = self.dataArr[indexPath.row];
    [cell.headImgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"userhead"]] placeholderImage:[UIImage imageNamed:@"headmoren"]];
    cell.name.text = [dic objectForKey:@"username"];
    cell.titleLab.text = [dic objectForKey:@"usersay"];
    
    
    return cell;
    
    
    
    
}

#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
